<?php
declare(strict_types=1);

namespace app\controller\user;

use app\controller\BaseController;
use app\model\{User, UserBalanceFlow, UserPaymentRecord, UserWithdrawRecord};
use app\service\LogService;
use think\facade\{Cache, Validate};

class WalletController extends BaseController
{
    /**
     * 获取钱包信息
     */
    public function info()
    {
        try {
            $userId = $this->request->user_id;
            $user = User::find($userId);
            
            if (!$user) {
                return $this->error('用户不存在');
            }
            
            return $this->success([
                'balance' => $user->balance,
                'frozen_balance' => $user->frozen_balance ?? 0,
                'total_income' => $user->total_income ?? 0,
                'total_withdraw' => $user->total_withdraw ?? 0
            ]);
            
        } catch (\Exception $e) {
            LogService::error('Wallet', sprintf(
                'Get wallet info failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取钱包信息失败');
        }
    }
    
    /**
     * 获取余额流水
     */
    public function flows()
    {
        try {
            $params = $this->request->get();
            
            $validate = Validate::rule([
                'page' => 'number|min:1',
                'limit' => 'number|between:1,50',
                'type' => 'in:1,2,3,4,5,6'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            $where = ['user_id' => $this->request->user_id];
            if (!empty($params['type'])) {
                $where['type'] = $params['type'];
            }
            
            $list = UserBalanceFlow::where($where)
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $params['limit'] ?? 20,
                    'page' => $params['page'] ?? 1
                ]);
            
            return $this->success($list);
            
        } catch (\Exception $e) {
            LogService::error('Wallet', sprintf(
                'Get balance flows failed: %s',
                $e->getMessage()
            ));
            return $this->error('获取余额流水失败');
        }
    }
    
    /**
     * 申请提现
     */
    public function withdraw()
    {
        try {
            $params = $this->request->post();
            
            $validate = Validate::rule([
                'amount' => 'require|float|gt:0',
                'withdraw_name' => 'require',
                'withdraw_account' => 'require',
                'withdraw_account_type' => 'require|in:alipay,bank,wechat'
            ]);
            
            if (!$validate->check($params)) {
                return $this->error($validate->getError());
            }
            
            $user = User::find($this->request->user_id);
            if (!$user) {
                return $this->error('用户不存在');
            }
            
            if ($user->balance < $params['amount']) {
                return $this->error('余额不足');
            }
            
            // 创建提现记录
            $withdraw = UserWithdrawRecord::create([
                'merchant_id' => $this->request->merchant_id,
                'user_id' => $user->id,
                'withdraw_amount' => $params['amount'],
                'withdraw_fee' => 0, // TODO: 计算手续费
                'withdraw_status' => 0,
                'withdraw_name' => $params['withdraw_name'],
                'withdraw_account' => $params['withdraw_account'],
                'withdraw_account_type' => $params['withdraw_account_type'],
                'create_time' => date('Y-m-d H:i:s')
            ]);
            
            // 冻结余额
            $user->balance -= $params['amount'];
            $user->frozen_balance = ($user->frozen_balance ?? 0) + $params['amount'];
            $user->save();
            
            return $this->success($withdraw);
            
        } catch (\Exception $e) {
            LogService::error('Wallet', sprintf(
                'Apply withdraw failed: %s',
                $e->getMessage()
            ));
            return $this->error('申请提现失败');
        }
    }
} 